<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户竞答轮次表
 */

class AnswerActivityUserCorrectNumber extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_correct_number';


    /**
     * 写入一轮答题记录
     */
    public function addUserCorrectNumber($data,$unit_id,$user_guid,$answer_time,$answer_number)
    {
        $this->act_id = $data[0]['act_id'];
        $this->user_guid = $user_guid;
        $this->unit_id = $unit_id ?: 0;
        $this->date = date('Y-m-d');
        $this->answer_number = $answer_number;
        $this->have_answer_number = 0;
        $this->correct_number = 0;
        $this->accuracy = 0;
        $this->status = 0;
        $this->times = $answer_time;
        $this->expire_time = date('Y-m-d H:i:s' , strtotime("+".$answer_time*$answer_number." second"));
        $this->save();

        return $this->id;
    }

    /**
     * 写入一轮答题记录
     */
    public function changeUserCorrectNumber($res, $success, $error , $times = null)
    {
        $res->have_answer_number = $success + $error;
        $res->correct_number = $success;

        $accuracy = $res->correct_number / $res->answer_number;
        $accuracy = sprintf("%.2f", $accuracy * 100);

        $res->accuracy = $accuracy;
        $res->status = 1;
        $res->times = $times ? $times : time() - strtotime($res->create_time);
        $res->save();

        return $res->id;
    }


    /**
     * 根据 id，获取此轮记录
     * @param $id
     */
    public function getCorrectRecordById($id){
        $res = $this->where('id', $id)->first();
        return $res;
    }

    /**
     * 获取今日的答题记录
     * @param $act_id
     * @param $unit_id
     * @param $exclude_correct_number_id 需要排除的id
     *  正确数高的排在第一位
     */
    public function getCorrectNumber($act_id , $unit_id ,$user_guid,$date, $order = 'correct_number desc' , $exclude_correct_number_id =null,$limit =1){
        $res = $this->where('act_id', $act_id)->where(function($query) use($unit_id ,$exclude_correct_number_id, $date){
            if($unit_id){
                $query->where('unit_id', $unit_id);
            }
            if($date){
                $query->where('date' , date('Y-m-d'));//获取今日次数
            }
            if($exclude_correct_number_id){
                $query->where('id' , '<>' , $exclude_correct_number_id);//排除的id
            }
        })->where('user_guid' , $user_guid)
        ->limit($limit)
        ->orderByRaw($order)
        ->get()
        ->toArray();
        return $res;
    }


}
